#!/usr/bin/env python
#coding=utf-8

from __future__ import division
import time
import sys
from define import BASE_DIR
sys.path.append(BASE_DIR)

#import pymongo
from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort

#需要修改
class api_cat_report_week(abstract_cron) :

    #需要修改
    #noLock = True   #是否生成脚本锁文件
    selectTable = 'sdb_statistics_api_cat_report_day'
    insertTable = 'sdb_statistics_api_cat_report_week'

    def __init__(self) :
        #需要修改
        super(api_cat_report_week,self).__init__(__file__)
        self.lastWeek = dateTypeInterval('last_week')
        self.currentWeek = dateTypeInterval('week')
        curWeekNum = sec2str('%W')
        lastWeekNum = sec2str('%W',time.time()-7*24*3600)
        self.dateIdent = '(第%s周)%s/%s' % (curWeekNum,self.currentWeek[0],self.currentWeek[1])
        self.weekFormat = '(第%s周)%s/%s' % (lastWeekNum,self.lastWeek[0],self.lastWeek[1])

    def boot(self,timestamp={}) :
#        self.preBoot()

        data = self.getData(timestamp)
        if data :
            for v in data :
                v['date'] = self.weekFormat
                self.figureRatio(v,'api_visit_num','api_fail_num','api_succ_ratio')
                #数据过滤
                self.filterItems(v)

            #批量插入
            self.doBatchExec()

        self.sufBoot()
        print 'ok'

    def getData(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        #外层sql 总量的只需要取该时间段最后一天的各量即可
        sql  = ' SELECT a.`calltime`,a.`date`,a.`api_visit_num_total`, '
        sql += ' a.`api_fail_num_total`,a.`api_succ_ratio_total`,b.* '
        sql += ' FROM `'+self.selectTable+'` AS a, '
        #内层sql 开始
        sql += ' ('
        sql += ' SELECT `api_cat`,SUM(`api_visit_num`) AS api_visit_num, '
        sql += ' SUM(`api_fail_num`) AS api_fail_num, MAX(`calltime`) AS max_calltime '
        sql += ' FROM `'+self.selectTable+'`'
        sql += ' WHERE '+self.db._filter(timeFilter)
        sql += ' GROUP BY `api_cat` '
        sql += ' ) AS b'
        #内层sql结束

        #外层sql where子句
        sql += ' WHERE a.`api_cat`=b.`api_cat` AND a.`calltime`=b.`max_calltime`'
        #确保每个类型只有一条数据
        sql += ' GROUP BY a.`api_cat`'
        row = self.db.select(sql)
        return row

    def getTimeFilter(self,timestamp=[]) :
        keyFilter = {}
        #time_begin = str2sec('2011-05-16','%Y-%m-%d')
        #time_end = str2sec('2011-05-31','%Y-%m-%d')
        time_begin = str2sec(self.lastWeek[0],'%Y-%m-%d')
        time_end = str2sec(self.lastWeek[1],'%Y-%m-%d')+1*24*3600
        keyFilter['calltime|between'] = timestamp and timestamp or [time_begin,time_end]
        return keyFilter

    def insertKeys(self) :
        return ['api_cat',
                'api_visit_num','api_visit_num_total',
                'api_fail_num','api_fail_num_total',
                'api_succ_ratio','api_succ_ratio_total',
                'date','calltime',
                ]


#需要修改
if __name__ == '__main__' :
    obj = api_cat_report_week()
    obj.boot()

    #obj.boot([time_begin,time_end])